package org.ykh.gmall.list.api;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.web.bind.annotation.*;
import org.ykh.gmall.list.Goods;
import org.ykh.gmall.list.SearchParam;
import org.ykh.gmall.list.SearchResponseVo;
import org.ykh.gmall.list.service.SearchService;
import org.ykh.gmall.result.Result;

@RestController
@RequestMapping("/api/list")
public class ListApiController {


//    @Autowired
//    private ElasticsearchRestTemplate restTemplate;

    //在ES7.x以下的版本使用的是ElasticsearchTemple，7.x以上版本已弃用ElasticsearchTemple，使用ElasticsearchRestTemple替代
    //ElasticsearchRestTemple是ElasticsearchOperations的子类的子类
    @Autowired
    ElasticsearchOperations elasticsearchOperations;

    @Autowired
    private SearchService searchService;

    /**
     * /api/list
     * 商品搜索
     * @param searchParam
     * @return
     */
    @PostMapping
    public Result search(@RequestBody SearchParam searchParam){

        SearchResponseVo responseVo=searchService.search(searchParam);

        return Result.ok(responseVo);
    }



    /**
     * 更新商品的热度排名
     * /api/list/inner/incrHotScore/{skuId}
     * @param skuId
     */
    @GetMapping("/inner/incrHotScore/{skuId}")
    public void  incrHotScore(@PathVariable Long skuId){

        searchService.incrHotScore(skuId);


    }




    /**
     * 商品的下架
     *   /api/list/inner/lowerGoods/{skuId}
     * @param skuId
     * @return
     */
    @GetMapping("/inner/lowerGoods/{skuId}")
    public Result lowerGoods(@PathVariable Long skuId){
        searchService.lowerGoods(skuId);

        return Result.ok();
    }


    /**
     * 商品上架
     * /api/list/inner/upperGoods/{skuId}
     * @return
     */
    @GetMapping("/inner/upperGoods/{skuId}")
    public  Result upperGoods(@PathVariable Long skuId){

        searchService.upperGoods(skuId);

        return Result.ok();
    }



    /**
     * 创建索引库
     *  /api/list/createIndex
     * @return
     */
    @GetMapping("createIndex")
    public Result createIndex(){
//        //创建索引库
//        restTemplate.createIndex(Goods.class);
//        //创建mappings
//        restTemplate.putMapping(Goods.class);

        IndexOperations indexOperations = elasticsearchOperations.indexOps(Goods.class);
        Document mapping = indexOperations.createMapping(Goods.class);
        indexOperations.create( mapping);


        return Result.ok("goods索引库创建成功！！");
    }



}
